from datetime import datetime
from enum import IntEnum
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
import os
import logging

#查找元素的类型
class find_type(IntEnum):
    css_type = 1
    xpath_type = 2

class windows_size_type:
    min = 1     #最小化
    max = 2     #最大化
    all = 3     #全屏
    custom = 4  #自定义尺寸

class Driver :
    driver = ""
    suffix_num = 0
    def __init__(self,path):
        self.service = Service(path)
        options = webdriver.ChromeOptions()
        self.driver = webdriver.Chrome(service=self.service,options = options)
    def __del__(self):
        print("驱动quit!")
        self.driver.quit()
    def get_driver(self):
        return self.driver
    def get(self,url):
        self.driver.get(url)
    def find_by_select(self,val):
        return self.driver.find_element(By.CSS_SELECTOR,val)
    def finds_by_select(self,val):
        ret = self.driver.find_elements(By.CSS_SELECTOR, val)
        return ret
    def find_by_xpath(self,path):
        return self.driver.find_element(By.XPATH,path)
    def finds_by_xpath(self,path):
        return self.driver.find_elements(By.XPATH,path)
    #发起点击事件
    def click(self,elem):
        return elem.click()
    #模拟按键输入
    def emulate_key_inputs(self,elem,text):
        elem.clear()
        return elem.send_keys(text)
    #清除按键键入的数据
    def clear(self,Type,val):
        if Type == find_type.css_type:
            self.find_by_select(val).clear()
        else:
            self.find_by_xpath(val).clear()
    #获取文本信息,注意不是属性信息
    def get_text_from_element(self,Type,val):
        if Type == find_type.css_type:
            return self.find_by_select(val).text
        else:
            return self.find_by_xpath(val).text
    #获取当前页面标题
    def get_current_title(self):
        return self.driver.title
    #获取当前页面的url
    def get_current_url(self):
        return self.driver.current_url
    #切换句柄--只能在2个不同的窗口之间进行切换
    def switch_to_window(self):
        #先获取当前所有的界面
        allWindows = self.driver.window_handles
        currentWindow = self.driver.current_window_handle
        #再遍历查找
        for handler in allWindows:
            if handler != currentWindow:
                self.driver.switch_to.window(handler)
                return True
        return False
    #设置窗口大小
    def set_current_windows_size(self,Type,w = None,h = None):
        if Type == windows_size_type.min:
            self.driver.minimize_window()
        elif Type == windows_size_type.max:
            self.driver.maximize_window()
        else:
            self.driver.set_window_size(w,h)
    #屏幕截图--抓拍--出错处理
    def log_to_image(self,func_name = None):
        save_filename = ""
        self.suffix_num += 1
        #先判断目录存在
        prefix = "../images/"
        #2025-6-16
        dirname = datetime.now().strftime("%Y-%m-%d")
        # ../images/2025-6-16
        if not os.path.exists(prefix+dirname):
            os.mkdir(prefix+dirname)
        filename = 'AutoTest-' + datetime.now().strftime("%Y-%m-%d-%Hh_%Mm_%Ss") +'-' + str(self.suffix_num) +'.png'
        if func_name is not None:
            save_filename += func_name
            save_filename += "-"
        try:
            self.driver.save_screenshot(prefix+dirname+"/"+save_filename+filename)
        except Exception as e:
            print(f"截图出错:{e}")
    # 关闭窗口,注意：窗⼝关闭后driver要重新定义--仅仅只是退出当前窗口
    def close(self):
        self.driver.close()
    def quit(self):
        self.driver.quit()
    #关于窗口 - alert
    #确认
    def accept_to_alert(self):
        alert = self.driver.switch_to.alert
        alert.accept()
    #取消
    def dismiss_to_alert(self):
        alert = self.driver.switch_to.alert
        alert.dismiss()
    #填充alert输入框(如果有)数据
    def input_to_alert(self,data):
        alert = self.driver.switch_to.alert
        alert.send_keys(data)
    def text_from_alert(self):
        alert = self.driver.switch_to.alert
        return alert.text
    #关于等待
    #隐式等待--作用域当前脚本所有作用域
    def wait(self,seconds):
        self.driver.implicitly_wait(seconds)
    #显示等待--只作用于与某一行
    def display_wait(self,sec,condition):
        wait = WebDriverWait(self.driver,sec)
        return wait.until(condition)
    #浏览器返回上一个页面
    def back(self):
        self.driver.back()
    #前进
    def forward(self):
        self.driver.forward()
    #刷新
    def refresh(self):
        self.driver.refresh()
BlogDriver = Driver('C:\driver\chromedriver-win64\chromedriver.exe')